package com.sea.supply.service.impl;



import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.codecrane.core.controller.UploaderController;
import com.codecrane.core.util.PdfReadUtils;
import com.codecrane.core.web.Ajax;
import com.codecrane.core.web.AjaxReturn;
import com.sea.physical.entity.CreateDistributeSku;
import com.sea.physical.entity.CreatePlan;
import com.sea.physical.service.CreateDistributeSkuService;
import com.sea.physical.service.CreatePlanService;
import com.sea.physical.service.CreateSkuService;
import com.sea.supply.entity.*;

import com.sea.supply.mapper.PdfFileMapper;
import com.sea.supply.mapper.PdfMapper;
import com.sea.supply.service.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author 陈鸿飞
 */
@Service
public class PdfServiceImpl implements PdfService {
    @Autowired
    private CreatePlanService createPlanService;
    @Autowired
    private CreateDistributeSkuService createDistributeSkuService;

    @Autowired
    private PdfMapper pdfMapper;

    @Autowired
    private PdfFileService pdfFileService;

    @Override
    public int save(PdfRead pdfRead) {
        return pdfMapper.insert(pdfRead);
    }

    @Override
    public void findPdfDetailByPlanNo(String strs){

        String[] split = strs.split(",");
        List<CreatePlan> list = createPlanService.findByCreatePlanNo(split);
        for (CreatePlan createPlan:list){

            List<CreateDistributeSku> dList = createDistributeSkuService.findTotalNumberByCreateId(createPlan.getId());
            for(CreateDistributeSku d:dList){
                double createBoxNumber = d.getCreateBoxNumber();
                List<PdfRead> pList = findBySku(d.getCreateSku(),createPlan.getCreatePlanNo(), (int) createBoxNumber);
                for(PdfRead p:pList){
                    p.setCreatePlanNo(createPlan.getCreatePlanNo());
                    p.setPdfSupplierName(d.getCreateSupplierName());
                    p.setFlag(1);
                    usave(p);
                }
            }
        }
    }

    @Override
    public int usave(PdfRead pdfRead) {
        return pdfMapper.update(pdfRead);
    }

    @Override
    public List<PdfRead> findBySku(String pdfSku,String createPlanNo, Integer number) {
        return pdfMapper.findBySku(pdfSku,createPlanNo,number);
    }

    @Override
    public void newPdf(String strs,String urlStr) throws MalformedURLException {
        String[] split = strs.split(",");
        List<CreatePlan> list = createPlanService.findByCreatePlanNo(split);
        for (CreatePlan createPlan : list) {
            List<PdfRead> pList = findSupplierName(createPlan.getCreatePlanNo());
            for (PdfRead p : pList) {
                List<PdfRead> rList = findBySupplierNameCreatePlanNo(createPlan.getCreatePlanNo(), p.getPdfSupplierName());

                // 创建输出流来存储新PDF内容
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                PDDocument newDocument = new PDDocument();

                URL url = new URL(urlStr);
                try (PDDocument sourceDocument = PDDocument.load(url.openStream())) {
                    for (PdfRead pageNum : rList) {
                        // 加载源PDF文件
                        PDPageTree pages = sourceDocument.getPages();
                        PDPage page = pages.get(pageNum.getPdfIndex()-1);
                        newDocument.addPage(page);
                    }
                    // 保存新的PDF文档到输出流
                    newDocument.save(outputStream);
                    newDocument.close();

                    // 获取包含新PDF内容的字节数组
                    byte[] newPdfContent = outputStream.toByteArray();

                    // 现在你可以将这些字节数组转换为输入流
                    InputStream newPdfInputStream = new ByteArrayInputStream(newPdfContent);

                    savePdfFile(createPlan.getCreatePlanNo(),p.getPdfSupplierName(),newPdfInputStream);
                    newPdfInputStream.close();
                    outputStream.close();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

    @Override
    public void newPdfSku(String sku, String urlStr) throws MalformedURLException {

        if (StringUtils.isNotBlank(sku)) {

            List<PdfRead> skuList = queryBySku(sku);

            // 创建输出流来存储新PDF内容
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            PDDocument newDocument = new PDDocument();

            URL url = new URL(urlStr);
            try (PDDocument sourceDocument = PDDocument.load(url.openStream())) {
                for (PdfRead pageNum : skuList) {
                    // 加载源PDF文件
                    PDPageTree pages = sourceDocument.getPages();
                    PDPage page = pages.get(pageNum.getPdfIndex() - 1);
                    newDocument.addPage(page);
                }
                // 保存新的PDF文档到输出流
                newDocument.save(outputStream);
                newDocument.close();

                // 获取包含新PDF内容的字节数组
                byte[] newPdfContent = outputStream.toByteArray();

                // 现在你可以将这些字节数组转换为输入流
                InputStream newPdfInputStream = new ByteArrayInputStream(newPdfContent);

                savePdfSkuFile(sku, "", newPdfInputStream);
                newPdfInputStream.close();
                outputStream.close();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
    }


    void savePdfFile(String createPlanNo,String supplierName,InputStream newPdfInputStream){
        OSSClient ossClient=new OSSClient("http://oss-cn-beijing.aliyuncs.com",
                "LTAI4G55LJEk8nARtrjYngou",
                "XPbdMs0xrRGAsmKVm9VYC8bSTTuFhl");

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("application/octet-stream");
        //修改后的文件名(带后缀)
        String NewFileName =  UUID.randomUUID().toString()+ ".pdf";
        ossClient.putObject("cozylux-pdf", NewFileName, newPdfInputStream,metadata);
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 50);
        String url = ossClient.generatePresignedUrl("cozylux-pdf", NewFileName, expiration).toString();

        PdfFile pdfFile=new PdfFile();
        pdfFile.setPdfPlanNo(createPlanNo);
        pdfFile.setPdfSupplierName(supplierName);
        pdfFile.setPdfFile(url);
        pdfFileService.save(pdfFile);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    void savePdfSkuFile(String createPlanNo,String supplierName,InputStream newPdfInputStream){
        OSSClient ossClient=new OSSClient("http://oss-cn-beijing.aliyuncs.com",
                "LTAI4G55LJEk8nARtrjYngou",
                "XPbdMs0xrRGAsmKVm9VYC8bSTTuFhl");

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentType("application/octet-stream");
        //修改后的文件名(带后缀)
        String NewFileName =  createPlanNo+ ".pdf";
        ossClient.putObject("cozylux-pdf", NewFileName, newPdfInputStream,metadata);
        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 50);
        String url = ossClient.generatePresignedUrl("cozylux-pdf", NewFileName, expiration).toString();

        PdfFile pdfFile=new PdfFile();
        pdfFile.setPdfPlanNo(createPlanNo);
        pdfFile.setPdfSupplierName(supplierName);
        pdfFile.setPdfFile(url);
        pdfFileService.save(pdfFile);
        // 关闭OSSClient。
        ossClient.shutdown();
    }

    @Override
    public List<PdfRead> findSupplierName(String createPlanNo) {
        return pdfMapper.findSupplierName(createPlanNo);
    }

    @Override
    public List<PdfRead> findBySupplierNameCreatePlanNo(String createPlanNo, String pdfSupplierName) {
        return pdfMapper.findBySupplierNameCreatePlanNo(createPlanNo, pdfSupplierName);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importPdfSku(MultipartFile importSession, String fileName, String createPlanNo) throws Exception {
        String[] split = createPlanNo.split(",");
        List<CreatePlan> list = createPlanService.findByCreatePlanNo(split);
        for (CreatePlan p : list) {
            Integer num = pdfFileService.findByCreatePlanNo(p.getCreatePlanNo()).size();
            if(num!=0){
                throw new RuntimeException("当前柜号已存在,请勿重复！【"+p.getCreatePlanNo()+"】");
            }
        }


        // 打开PDF文件
        PDDocument document = PDDocument.load(importSession.getInputStream());
        // 获取PDF文档的总页数
        int numberOfPages = document.getNumberOfPages();
        // 创建PDFTextStripper对象
        PDFTextStripper pdfStripper = new PDFTextStripper();

        // 遍历每一页
        for (int page = 1; page <= numberOfPages; page++) {
            PdfRead pdfRead = new PdfRead();
            pdfStripper.setStartPage(page);
            pdfStripper.setEndPage(page);

            // 获取当前页的文本内容
            String text = pdfStripper.getText(document);
            System.out.println("Page " + text + ":");
            // 打印当前页的页码和文本内容
            System.out.println("Page " + page + ":");
            String readSku = PdfReadUtils.readPdfSku(text);
            if(StringUtils.isBlank(readSku)){
                readSku = PdfReadUtils.readPdfSku2(text);
            }
            if(StringUtils.isBlank(readSku)){
               throw new RuntimeException("获取SKU信息异常，请联系管理员");
            }
            String pdfNumber = PdfReadUtils.readPdfNumber(text);
            String pdfShipmentId = PdfReadUtils.readPdfShipmentId(text);

            System.out.println("【" + readSku + "】");
            System.out.println("【" + pdfNumber + "】");

            pdfRead.setPdfSku(readSku);
            pdfRead.setPdfNumber(Integer.parseInt(pdfNumber));
            pdfRead.setPdfIndex(page);
            pdfRead.setPdfPlanNo(createPlanNo);
            pdfRead.setPdfShipmentId(pdfShipmentId);
            save(pdfRead);
        }
        //读取完PDF以后分到对应的柜号里
        findPdfDetailByPlanNo(createPlanNo);
        String file = getFile(importSession);
        if (StringUtils.isNotBlank(file)) {
            newPdf(createPlanNo, file);
        } else {
            throw new RuntimeException("获取文件异常！");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void importPdfBySku(MultipartFile importSession, String fileName) throws Exception {

        clearPdfSku();
        pdfFileService.clearPdfFile();
        // 打开PDF文件
        PDDocument document = PDDocument.load(importSession.getInputStream());
        // 获取PDF文档的总页数
        int numberOfPages = document.getNumberOfPages();
        // 创建PDFTextStripper对象
        PDFTextStripper pdfStripper = new PDFTextStripper();

        // 遍历每一页
        for (int page = 1; page <= numberOfPages; page++) {
            PdfRead pdfRead = new PdfRead();
            pdfStripper.setStartPage(page);
            pdfStripper.setEndPage(page);

            // 获取当前页的文本内容
            String text = pdfStripper.getText(document);
            System.out.println("Page " + text + ":");
            // 打印当前页的页码和文本内容
            System.out.println("Page " + page + ":");
            String readSku = PdfReadUtils.readPdfSku(text);

            String pdfNumber = PdfReadUtils.readPdfNumber(text);

            System.out.println("【" + readSku + "】");
            System.out.println("【" + pdfNumber + "】");

            pdfRead.setPdfSku(readSku);
            pdfRead.setPdfNumber(Integer.parseInt(pdfNumber));
            pdfRead.setPdfIndex(page);

            save(pdfRead);
        }

        String file = getFile(importSession);
        if (StringUtils.isNotBlank(file)) {
            List<PdfRead> list = groupBySku();
            if(null!=list && list.size() !=0){
                for(PdfRead pdfRead:list){
                    newPdfSku(pdfRead.getPdfSku(), file);
                }
            }

        } else {
            throw new RuntimeException("获取文件异常！");
        }



    }


    @Override
    public List<PdfRead> findByPdfPlanNo(PdfFile pdfFile) {
        return pdfMapper.findByPdfPlanNo(pdfFile);
    }

    @Override
    public void deleteByPdfPlanNo(String pdfPlanNo) {
        String[] split = pdfPlanNo.split(",");
        for(String createPlanNo:split){
            pdfFileService.deleteByPdfPlanNo(createPlanNo);
        }
        pdfMapper.deleteByPdfPlanNo(pdfPlanNo);

    }

    @Override
    public Integer clearPdfSku() {
        return pdfMapper.clearPdfSku();
    }

    @Override
    public List<PdfRead> groupBySku() {
        return pdfMapper.groupBySku();
    }

    @Override
    public List<PdfRead> queryBySku(String pdfSku) {
        return pdfMapper.queryBySku(pdfSku);
    }

    public String getFile(MultipartFile importSession) {
        AjaxReturn result = Ajax.fail().setMsg("上传失败！");
        try {
            OSSClient ossClient=new OSSClient("http://oss-cn-beijing.aliyuncs.com",
                    "LTAI4G55LJEk8nARtrjYngou",
                    "XPbdMs0xrRGAsmKVm9VYC8bSTTuFhl");
            InputStream inputStream = importSession.getInputStream();
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType("application/octet-stream");
            String filename = importSession.getOriginalFilename();
            //获取文件后缀名
            String prefix=filename.substring(filename.lastIndexOf(".")+1);
            // //修改后的文件名
            String fileUUIDname = UUID.randomUUID().toString();
            //修改后的文件名(带后缀)
            String NewFileName = fileUUIDname + "." + prefix;
            ossClient.putObject("cozylux", NewFileName, inputStream,metadata);
            // 关闭OSSClient。
            ossClient.shutdown();
            Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 50);
            return ossClient.generatePresignedUrl("cozylux", NewFileName, expiration).toString();
        }catch (Exception e){
            return null;
        }
    }

    public static void main(String[] args) {
        // PDF文件的路径
        String filePath = "F:\\test.pdf";

        // 打开PDF文件
        try (PDDocument document = PDDocument.load(new File(filePath))) {
            // 获取PDF文档的总页数
            int numberOfPages = document.getNumberOfPages();

            // 创建PDFTextStripper对象
            PDFTextStripper pdfStripper = new PDFTextStripper();

            // 遍历每一页
            for (int page = 1; page <= numberOfPages; page++) {
                pdfStripper.setStartPage(page);
                pdfStripper.setEndPage(page);

                // 获取当前页的文本内容
                String text = pdfStripper.getText(document);

                // 打印当前页的页码和文本内容
                System.out.println("Page " + page + ":");
                System.out.println(text);
                System.out.println("--------------------------------------------------");
                System.out.println("拆分SKU:"+PdfReadUtils.readPdfSku(text));

            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
